package com.bensonbasement.snorflux.client;

import java.util.ArrayList;

import javax.swing.AbstractListModel;

import com.bensonbasement.snorflux.messages.fromserver.PlayerInfo;
import com.bensonbasement.snorflux.messages.fromserver.PlayerStatus;


public class PlayerListModel extends AbstractListModel {
	
	private ArrayList<PlayerInfo> players = new ArrayList<PlayerInfo>();
	
	@Override
	public Object getElementAt(int i) {
		return players.get(i);
	}

	@Override
	public int getSize() {
		return players.size();
	}
	
	public void updateInfo(String playerName, PlayerStatus status) {
		for (int i = 0; i < players.size(); i++) {
			if (players.get(i).getPlayerName().equals(playerName)) {
				PlayerInfo info = new PlayerInfo(playerName,status);
				players.set(i, info);
				fireContentsChanged(this, i, i);
				return;
			}
		}
		throw new RuntimeException("Trying to update info for a non-existent player.");
	}
	
	public void addInfo(PlayerInfo info) {
		players.add(info);
		int index = players.size() - 1;
		fireIntervalAdded(this, index, index);
	}
	
	public void removeInfo(String playerName) {
		for (int i = 0; i < players.size(); i++) {
			if (players.get(i).getPlayerName().equals(playerName)) {
				players.remove(i);
				fireIntervalRemoved(this, i, i);
				return;
			}
		}
		throw new RuntimeException("Trying to remove info for a non-existent player.");
	}
	
//	public boolean containsInfo(String playerName) {
//		for (PlayerInfo player : players) {
//			if (player.getPlayerName().equals(playerName)) {
//				return true;
//			}
//		}
//		return false;
//	}
	
	// TODO: This method should probably be removed
	// (should build a new PlayerListModel instead of
	// refreshing this one.
	public void clear() {
		players.clear();
	}
}
